<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">
        <h2>后台管理系统</h2>
        <p>欢迎登录</p>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="off"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            prefix-icon="User"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            autocomplete="new-password"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              size="large"
              prefix-icon="Picture"
              maxlength="4"
              @keyup.enter="handleLogin"
            />
            <div class="captcha-image" @click="refreshCaptcha" v-html="captchaSvg" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            class="login-button"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { getCaptcha, login, type LoginParams } from '@/api/auth'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const captchaLoading = ref(false)
const captchaSvg = ref('')
const captchaId = ref('')

const loginForm = reactive<LoginParams & { username: string; password: string; captcha: string }>({
  username: 'admin',
  password: 'Admin123',
  captchaId: '',
  captcha: ''
})

const loginRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为4位', trigger: 'blur' }
  ]
}

// 加载验证码
const loadCaptcha = async () => {
  captchaLoading.value = true
  try {
    const res = await getCaptcha()
    captchaSvg.value = res.data.svg
    captchaId.value = res.data.id
    loginForm.captchaId = res.data.id
    loginForm.captcha = '' // 清空验证码输入
  } catch (error: any) {
    ElMessage.error(error.message || '加载验证码失败')
  } finally {
    captchaLoading.value = false
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  loadCaptcha()
}

const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        // 使用新的登录接口，包含验证码
        const loginParams: LoginParams = {
          username: loginForm.username,
          password: loginForm.password,
          captchaId: loginForm.captchaId,
          captcha: loginForm.captcha
        }
        
        const res = await login(loginParams)
        
        // 保存 token
        const token = res.data.token
        userStore.token = token
        localStorage.setItem('portal-admin-token', token)
        
        // 清除验证码，准备下次登录
        loginForm.captcha = ''
        
        // 获取用户信息
        await userStore.getUserInfoAction()
        
        ElMessage.success('登录成功')
        const redirect = (route.query.redirect as string) || '/'
        router.push(redirect)
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败')
        // 登录失败后刷新验证码
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  loadCaptcha()
})
</script>

<style scoped lang="scss">
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  .login-box {
    width: 400px;
    padding: 40px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);

    .login-title {
      text-align: center;
      margin-bottom: 30px;

      h2 {
        font-size: 24px;
        color: #303133;
        margin-bottom: 10px;
      }

      p {
        font-size: 14px;
        color: #909399;
      }
    }

    .login-form {
      .login-button {
        width: 100%;
      }

      .captcha-container {
        display: flex;
        gap: 10px;
        width: 100%;

        .el-input {
          flex: 1;
        }

        .captcha-image {
          width: 120px;
          height: 40px;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #f5f7fa;
          transition: all 0.3s;

          &:hover {
            border-color: #409eff;
          }

          :deep(svg) {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
}
</style>

